<?php

class AjaxController extends Zend_Controller_Action
{
	function indexAction()
	{
		echo "Ajax";die;
	}
	
	function getCitiesAction()
	{
		$params = $this->_request->getParams();
		
		$result = array(
			'result' => 0
		);
		
		if($params['provinceId'])
		{
			if($params['type'])
			{
				$type = $params['type'];
			}else{
				$type = 1;
			}
			
			$dealers_db = Zend_Registry::get("dealers_db");
			$select = $dealers_db->select();
			$select->from("b_bu_auth", "*");
			$select->where("emp_id = ?", $_SESSION['identity']['userid']);
			$row = $dealers_db->fetchRow($select);
			
			$my_city_id_arr = explode("|", $row['city_id_txt']);
			
			if(!$my_city_id_arr[0])
			{
				$my_city_id_arr = NULL;
			}
			
			$mod_t_area = new Db_Tables2_TArea();
			$city_list = $mod_t_area->GetCities($params['provinceId'], $type, $my_city_id_arr);
			
			$result = array(
				'result' => 1,
				'data' => $city_list
			);
		}
		
		echo Zend_Json::encode($result); //back to ajax
    	die;
	}
	
	function getCountiesAction()
	{
		$params = $this->_request->getParams();
		
		$result = array(
			'result' => 0
		);
		
		if($params['cityId'])
		{
			$mod_t_region = new Db_Tables2_TRegion();
			$county_list = $mod_t_region->GetCounties($params['cityId']);
			
			$result = array(
				'result' => 1,
				'data' => $county_list
			);
		}
		
		echo Zend_Json::encode($result); //back to ajax
    	die;
	}
	
	function signerOptAction()
	{
		$params = $this->_request->getParams();
		
		$result = array(
			'result' => 0
		);
		
		if($params['id'] && is_numeric($params['status']))
		{
			$auth = 0;
			$dealers_db = Zend_Registry::get('dealers_db');
			
			if("LEVEL-3" == $_SESSION['identity']['level']) //合同管理员直接获得修改权限
			{
				$auth = 1;
			}elseif(2 == $params['status']){ //原作者允许在未通过时撤销
				$select = $dealers_db->select();
				$select->from("b_signer", array("emp_id", "status"));
				$select->where("signer_id = ?", $params['id']);
				$row = $dealers_db->fetchRow($select);
				
				if($row)
				{
					if(0 == $row['status'] && $_SESSION['identity']['userid'] == $row['emp_id'])
					{
						$auth = 1;
					}
				}
			}
			
			if($auth) //获得授权，开始操作
			{
				$set = array("status" => $params['status']);
				$where = "signer_id=".$params['id'];
				
				if($dealers_db->update("b_signer", $set, $where))
				{
					$result['result'] = 1;
				}
			}
		}
		
		echo Zend_Json::encode($result); //back to ajax
    	die;
	}
	
	function ownerOptAction()
	{
		$params = $this->_request->getParams();
		
		$result = array(
			'result' => 0
		);
		
		if($params['id'] && is_numeric($params['status']) && "LEVEL-3" == $_SESSION['identity']['level']) //合同管理员才有修改权限
		{
			$dealers_db = Zend_Registry::get('dealers_db');
			
			$set = array("status" => $params['status']);
			$where = "owner_id=".$params['id'];
			
			if($dealers_db->update("b_owner", $set, $where))
			{
				$result['result'] = 1;
			}
		}
		
		echo Zend_Json::encode($result); //back to ajax
    	die;
	}
	
	function bindSignerOptAction()
	{
		$params = $this->_request->getParams();
		
		$result = array(
			'result' => 0
		);
		
		if($params['id'] && is_numeric($params['status']) && "LEVEL-3" == $_SESSION['identity']['level']) //合同管理员才有修改权限
		{
			$dealers_db = Zend_Registry::get('dealers_db');
			
			$set = array("status" => $params['status']);
			$where = "id=".$params['id'];
			
			if($dealers_db->update("b_client_signer", $set, $where))
			{
				$result['result'] = 1;
			}
		}
		
		echo Zend_Json::encode($result); //back to ajax
    	die;
	}
	
	function contractOptAction()
	{
		$params = $this->_request->getParams();
		
		$result = array(
			'result' => 0
		);
		
		if($params['id'] && is_numeric($params['status']))
		{
			$the_status = $params['status'];
			
			$result['contract_id'] = $params['id'];
			
			$auth = 0;
			$level = 1;
			$dealers_db = Zend_Registry::get('dealers_db');
			
			if(in_array($_SESSION['identity']['level'], array("LEVEL-3", "LEVEL-4"))) //合同管理员和财务直接获得修改权限
			{
				$auth = 1;
				$level = 3;
			}elseif("LEVEL-2" == $_SESSION['identity']['level']){
				$select = $dealers_db->select();
				$select->from("b_contract", array("status"));
				$select->where("contract_id = ?", $params['id']);
				$row = $dealers_db->fetchRow($select);
				
				if($row)
				{
					if(in_array($row['status'], array(0,1,5,7)))
					{
						$auth = 1;
						$level = 2;
					}
				}
			}elseif("LEVEL-1" == $_SESSION['identity']['level']){
				$select = $dealers_db->select();
				$select->from("b_contract", array("status"));
				$select->where("contract_id = ?", $params['id']);
				$row = $dealers_db->fetchRow($select);
				
				if($row)
				{
					if(0 == $row['status'])
					{
						$auth = 1;
					}
				}
			}
			
			if($auth) //获得授权，开始操作
			{
				$set = array();
				$is_proceed = 0;
					
				if(0 == $params['status']) //驳回允许修改
				{
					$set['allow_edit'] = 1;
					$the_status = 98;
				}elseif(7 == $params['status']) //作废则关闭这个选项
				{
					$set['allow_edit'] = 0;
					
					//删除未回款的回款计划
					$mod_pay_plan = new Db_Tables2_BLogsContractPayPlan();
					$mod_pay_plan->CancelLog($params['id']);
				}
				
				if(2 == $level)
				{
					$set['emp_id_2'] = $_SESSION['identity']['userid'];
					
					//update leader's log
					if("LEVEL-2" == $_SESSION['identity']['level'] && 1 == $params['status'])
					{
						$mod_approval = new Db_Tables2_BLogsSalesApproval();
						$next_result = $mod_approval->MoveToNext(2, $params['id'], $_SESSION['identity']['userid']);
						
						if($next_result) //后面还有主管未审批
						{
							$is_proceed = 1;
							unset($set['status']); //不改合同状态
							
							$the_status = 0;
						}
					}
				}
				
				$pay_type = 0;
				
				$select = $dealers_db->select();
				$select->from("b_contract", "*");
				$select->where("contract_id = ?", $params['id']);
				$row = $dealers_db->fetchRow($select);

				$pay_type = $row['pay_type'];

				if(3 == $level)
				{
					$set['emp_id_3'] = $_SESSION['identity']['userid'];
					
					if(2 == $params['status'] && !$row['contract_sid'])
					{
//						$ext = new Sys_Extensions();
//						$set['contract_sid'] = $ext->GenerateOrderSid();
//						$set['sign_date'] = date("Y-m-d");
						
						//New Program Mark 2019.8.17
						$mod_contract_sku = new Db_Tables2_BContractSku();
						$product_id = $mod_contract_sku->GetProductId($params['id']);

						if($product_id)
						{
							$mod_product = new Db_Tables2_BDictProduct();
							$set['contract_sid'] = $mod_product->GenerateOrderSid($product_id);
							$set['sign_date'] = date("Y-m-d");
						}
					}
				}
				
				if(!$is_proceed)
				{
					$set['status'] = $params['status'];
				}
				
				$where = "contract_id=".$params['id'];
				
				$dealers_db->update("b_contract", $set, $where);
				$result['result'] = 1;
				
				if((in_array($pay_type, array(2,4)) || 0 == $row['contract_value']) && 3 == $level) //后付费或免费合同 且是合同管理员
				{
					$mod_contract = new Db_Tables2_BContract();
					$mod_contract->LaunchSwitcher($params['id'], 1, 1); //直接执行 等待执行主管确认
				}
				
				//写入审批日志
				$mod_logs_approval = new Db_Tables2_BLogsContractApproval();
				$mod_logs_approval->AddRecord($params['id'], $_SESSION['identity']['userid'], $_SESSION['identity']['realname'], $the_status);
			}
		}
		
		echo Zend_Json::encode($result); //back to ajax
    	die;
	}
	
	function getClientListAction()
	{
		$params = $this->_request->getParams();
		
		$result = array(
			'result' => 0
		);
		
		if($params['kw'])
		{
			$mod_client = new Db_Tables2_BClient();
			$data = $mod_client->GetClientArr($params['kw']);
			
			if(!empty($data))
			{
				$result = array(
					'result' => 1,
					'data' => $data
				);
			}
		}
		
		echo Zend_Json::encode($result); //back to ajax
    	die;
	}
	
	function getDealerListAction()
	{
		$params = $this->_request->getParams();
		
		$result = array(
			'result' => 0
		);
		
		if($params['kw'])
		{
			$mod_dealer = new Db_Tables2_TDealer();
			$data = $mod_dealer->GetDealerArr($params['kw']);
			
			if(!empty($data))
			{
				$result = array(
					'result' => 1,
					'data' => $data
				);
			}
		}
		
		echo Zend_Json::encode($result); //back to ajax
    	die;
	}
	
	function clientOptAction()
	{
		$params = $this->_request->getParams();
		
		$result = array(
			'result' => 0
		);
		
		if($params['id'] && is_numeric($params['status']))
		{
			$auth = 0;
			$dealers_db = Zend_Registry::get('dealers_db');
			
			if(in_array($_SESSION['identity']['level'], array("LEVEL-2", "LEVEL-3")))
			{
				$auth = 1;
			}
			
			if($auth) //获得授权，开始操作
			{
				$set = array(
					"status" => $params['status'],
					"emp_id_3" => $_SESSION['identity']['userid']
					);
				
				$where = "client_id=".$params['id'];
				
				if($dealers_db->update("b_client", $set, $where))
				{
					$result['result'] = 1;
					
					//update leader's log 取消主管审批，暂时注释 2019.8.8 Mark
//					if("LEVEL-2" == $_SESSION['identity']['level'])
//					{
//						$mod_approval = new Db_Tables2_BLogsSalesApproval();
//						$mod_approval->MoveToNext(1, $params['id'], $_SESSION['identity']['userid']);
//					}
				}
			}
		}
		
		echo Zend_Json::encode($result); //back to ajax
    	die;
	}
	
	function getSkuAction()
	{
		$params = $this->_request->getParams();
		
		$result = array(
			'result' => 0
		);
		
		$display_platform = 0;
		$is_product = 0;
		
		if($params['id'] && $params['type'])
		{
			if(1 == $params['type'])
			{
				$mod_products = new Db_Tables2_BDictProduct();
				$product = $mod_products->FetchProductDetails($params['id']);
				$display_platform = $product['display_platform'];
				
				$is_product = 1;
			}
			
			$dealers_db = Zend_Registry::get("dealers_db");
			$select = $dealers_db->select();
			$select->from("b_sku", "*");
			
			if(1 == $params['type'])
			{
				$select->where("product_id = ?", $params['id']);
			}else{
				$select->where("parent_sku_id = ?", $params['id']);
			}
			
			$select->where("status = ?", 1);
			
			$rows = $dealers_db->fetchAll($select);
			
			if($rows) //是分类
			{
				$options = array();
				
				foreach($rows as $row)
				{
					//排除直接通过菜单点击进来创建充值合同的情况 Mark 2019.5.20
					//允许修改合同时显示充值服务 2019.9.8
					if($_SESSION['contract']['contract_info']['parent_contract_id'] || (!$_SESSION['contract']['contract_info']['parent_contract_id'] && 961 != $row['sku_id']) || $params['in_edit_mode'])
					{
						$options[] = array(
							"sku_id" => $row['sku_id'],
							"sku_name" => $row['sku_name']
						);
					}
				}
				
				$result = array(
					'result' => 1,
					'type' => 1, //是分类
					'options' => $options,
					'sku_space_count' => $params['sku_space_count'],
					'display_platform' => $display_platform,
					'is_product' => $is_product
				);
			}elseif(2 == $params['type']){ //是sku
				$select = $dealers_db->select();
				$select->from("b_sku", "*");
				$select->where("sku_id = ?", $params['id']);
				$row = $dealers_db->fetchRow($select);
				
				if($row)
				{
					$result = array(
						'result' => 1,
						'type' => 2, //是sku
						'sku_info' => array(
							'sku_id' => $row['sku_id'],
							'product_id' => $row['product_id'],
                            'hxb_account' => $row['hxb_account'],
                            'parent_sku_id' => $row['parent_sku_id'],
							'sku_name' => $row['sku_name'],
							'unit_name' => $row['unit_name'],
							'unit_price' => $row['unit_price']
						)
					);
					
					if(2 == $_SESSION['contract']['contract_info']['contract_type_id']) //免费合同
					{
						$result['sku_info']['unit_price'] = 0;
					}
				}
			}
			
			
		}
		
		echo Zend_Json::encode($result); //back to ajax
    	die;
	}
	
	function addSkuIntoContractAction()
	{
		$params = $this->_request->getParams();
		
		$result = array(
			'result' => 0
		);
		
		if($params['sku_id'] && $params['new_sku_quantity'])
		{
			$_SESSION['contract']['sku_info'][] = array(
				"sku_id" => $params['sku_id'],
				"sku_quantity" => $params['new_sku_quantity'],
				"actual_pay" => $params['new_actual_pay']
			);
			
			$result = array(
				'result' => 1
			);
		}
		
		echo Zend_Json::encode($result); //back to ajax
    	die;
	}
	
	function saveContractInfoToSessionAction()
	{
		$params = $this->_request->getParams();
		
		$result = array(
			'result' => 0
		);
		
		if($params['contract_id'])
		{
			$target_session = $_SESSION['contract-edit-type2'][$params['contract_id']];	
		}else{
			$target_session = $_SESSION['contract'];
		}

		if($target_session)
		{
			$target_session['contract_info']['sign_date'] = $params['sign_date'];
			$target_session['contract_info']['signer_id'] = $params['signer_id'];
			$target_session['contract_info']['pay_type'] = $params['pay_type'];
			$target_session['contract_info']['tips'] = $params['tips'];
			$target_session['contract_info']['sign_type'] = $params['sign_type'];
			$target_session['contract_info']['invoice_type'] = $params['invoice_type'];
			$target_session['contract_info']['key_account_sales'] = $params['key_account_sales'];
			
			if(is_numeric($params['signer_id']))
			{
				$mod_signer = new Db_Tables2_BSigner();
				$signer = $mod_signer->FetchSignerDetails($params['signer_id']);
				$target_session['contract_info']['signer_company_name'] = $signer['company_name'];
			}else{
				$target_session['contract_info']['signer_company_name'] = NULL;
			}
			
			$target_session['contract_info']['owner_id'] = $params['owner_id'];
			
			$mod_owner = new Db_Tables2_BOwner();
			$owner = $mod_owner->FetchOwnerDetails($params['owner_id']);
			$target_session['contract_info']['owner_name'] = $owner['owner_name'];
			
			$target_session['contract_info']['contract_cost'] = $params['contract_cost'];
			
			if($params['contract_id'])
			{
				$_SESSION['contract-edit-type2'][$params['contract_id']] = $target_session;	
			}else{
				$_SESSION['contract'] = $target_session;
			}
			
			$result = array(
				'result' => 1
			);
		}
		
		echo Zend_Json::encode($result); //back to ajax
    	die;
	}
	
	function cancelContractInSessionAction()
	{
		unset($_SESSION['contract']);
		
		$result = array(
			'result' => 1
		);
		
		echo Zend_Json::encode($result); //back to ajax
    	die;
	}
	
	function delContractOptAction()
	{
		$params = $this->_request->getParams();
		
		$result = array(
			'result' => 0,
			'contract_id' => 0
		);
		
		if($params['lid'])
		{
			$dealers_db = Zend_Registry::get('dealers_db');
			
			$where = "lid = ".intval($params['lid']);
			
			$select = $dealers_db->select();
			$select->from("b_logs_contract", "*");
			$select->where("lid = ?", $params['lid']);
			$row = $dealers_db->fetchRow($select);
			
			if($row)
			{
				if($row['contract_id'])
				{
					if($dealers_db->delete("b_logs_contract", $where))
					{
						//update contract values
						$mod_contract = new Db_Tables2_BContract();
						$mod_contract->UpdateContractValue($row['contract_id'], 2, $row['value']);
						
						$result['result'] = 1;
						$result['contract_id'] = $row['contract_id'];
					}
				}
			}
		}
		
		echo Zend_Json::encode($result); //back to ajax
    	die;
	}

	function saveContractSignDateAction(){
        if("LEVEL-4" != $_SESSION['identity']['level'])
        {
            echo "无此权限";
            die;
        }

        $params = $this->_request->getParams();
        $result = array(
            'result' => 0
        );


        if($params['contract_id'] && $params['sign_date'])
        {
            $mod_bcontract = new Db_Tables2_BContract();
            $mod_bcontract->UpdateContractSignDate($params['contract_id'], $params['sign_date']);
            $result = array(
                'result' => 1
            );
        }
        echo Zend_Json::encode($result); //back to ajax
        die;
    }
	
	function get961DiscountAction()
	{
		$params = $this->_request->getParams();
		
		$result = array(
			'result' => 0,
			'value' => 0
		);
		
		if(is_numeric($params['value']))
		{
			$mod_961 = new Db_Tables2_BSku961Rules();
			$result['value'] = $mod_961->GetDiscountValue($params['value']);
			$result['result'] = 1;
		}
		
		echo Zend_Json::encode($result); //back to ajax
    	die;
	}
	
	function cellphoneAvailableAction()
	{
		$params = $this->_request->getParams();
		
		$result = array(
			'result' => 0
		);
		
		if($params['cellphone'])
		{
			$maozhua_wb = Zend_Registry::get('maozhua_wb');
			
			$select = $maozhua_wb->select();
			$select->from("dcc_users", "*");
			$select->where("cellphone = ?", trim($params['cellphone']));
			
			if($params['user_id'])
			{
				$select->where("user_id != ?", $params['user_id']);
			}
			
			$row = $maozhua_wb->fetchRow($select);
			
			if(empty($row))
			{
				$result['result'] = 1;
			}
		}
		
		echo Zend_Json::encode($result); //back to ajax
    	die;
	}

	function searchDealerIdAction()
    {
        $params = $this->_request->getParams();
        if($params['name'])
        {
            $dealers_db = Zend_Registry::get("dealers_db");
            $select = $dealers_db->select();
            $select->from("t_dealer", array("companyName","id"));
            $select->where("companyName = ?", $params['name']);
            $row = $dealers_db->fetchRow($select);
            $result['id'] = '';
            if($row)
            {
                $result['id'] = $row['id'];
            }
            echo Zend_Json::encode($result);
            die;
        }
    }

    function usernameCheckAction()
    {
        $params = $this->_request->getParams();
        $result = array(
            'result' => 0,
            'reason' => "未知错误"
        );

        if($params['username'])
        {
            $username = trim($params['username']);
        }else{
            $username = NULL;
        }

        if($username)
        {
            $hxb_db = Zend_Registry::get('hxb_db');
            $select = $hxb_db->select();
            $select->from("auth_emp", array("id"));
            $select->where("username = ?", $username);

            if($params['exclude_id'])
            {
                $select->where("id != ?", $params['exclude_id']);
            }

            $row = $hxb_db->fetchRow($select);

            if($row)
            {
                $result = array(
                    'result' => 0,
                    'reason' => "登录名已被占用，请更换登录名"
                );
            }else{
                $result = array(
                    'result' => 1,
                    'reason' => "登录名可用"
                );
            }
        }

        echo Zend_Json::encode($result); //back to ajax
        die;
    }
}